<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户的数据表</title>
    <link rel="stylesheet" type="text/css" href="/static/CSS/scrollBar.css"/>
    <script type="text/javascript" src="/static/JS/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="/static/JS/echarts.min.js"></script>
    <script type="text/javascript" src="/static/JS/public.js"></script>
    <style>
        body{
            background-color: rgb(240,240,240);
            margin: 5px;
        }
        .charts .chart-container{
            width: 600px;
            display: inline-block;
            padding: 0 5px 10px 10px;
            vertical-align: bottom;
        }
        .charts input{
            border:none;
        }
        .noChart{
            width: 200px;
            height: 50px;
            position: absolute;
            top: calc(50% - 25px);
            left: calc(50% - 100px);
            color: #F63636
        }
    </style>
</head>
<body>
<script>
let host = "http://127.0.0.1:5000/api/";

// 计算字符的宽度font-size=12默认双字节为12,单字节为3
function getStrWidth(str, px){
    let realWidth = 0
    for (let i=0;i<str.length;i++){
        if (str.charCodeAt(i) > 255){
            realWidth += px
        }else{
            realWidth += px / 4
        }
    }
    return realWidth
}

// 生成水印
function generateGraphic(watermark, bottom){
    if(watermark === '' || watermark === undefined){return null}
    // else{
    //     return {
    //         type: 'group',
    //         rotation: Math.PI / 4,
    //         bounding: 'raw',
    //         right: 80,
    //         bottom: 80,
    //         z: -100,
    //         children: [
    //             {
    //                 type: 'rect',
    //                 left: 'center',
    //                 top: 'center',
    //                 z:-100,
    //                 shape:{width: 400, height: 35},
    //                 style:{fill: 'rgba(0,0,0,0.4)'}
    //             },
    //             {
    //                 type: 'text',
    //                 left: 'center',
    //                 top: 'center',
    //                 z: -100,
    //                 style: {
    //                     fill: 'rgba(255,255,255,0.9)',
    //                     text: watermark,
    //                     font: 'bold 22px Microsoft YaHei'
    //                 }
    //             }
    //         ]
    //     }
    // }
    else{
        return [{
            type: 'group',
            rotation: Math.PI / 4,
            bounding: 'raw',
            // right: 80,
            // bottom: 80,
            left: '35%',
            top: '25%',
            z: -100,
            children: [
                // {
                //     type: 'rect',
                //     left: 'center',
                //     top: 'center',
                //     z:-100,
                //     shape:{width: 400, height: 35},
                //     style:{fill: 'rgba(0,0,0,0.4)'}
                // },
                {
                    type: 'text',
                    left: 'center',
                    top: 'center',
                    z: -100,
                    style: {
                        fill: 'rgba(255,255,255,0.9)',
                        text: watermark,
                        font: '22px Microsoft YaHei'
                    }
                }
            ]
        }, {
            type: 'group',
            rotation: Math.PI / 4,
            bounding: 'raw',
            // right: 80,
            // bottom: 80,
            right: '35%',
            top: '50%',
            z: -100,
            children: [
                // {
                //     type: 'rect',
                //     left: 'center',
                //     top: 'center',
                //     z:-100,
                //     shape:{width: 400, height: 35},
                //     style:{fill: 'rgba(0,0,0,0.4)'}
                // },
                    {
                        type: 'text',
                        left: 'center',
                        top: 'center',
                        z: -100,
                        style: {
                            fill: 'rgba(255,255,255,0.9)',
                            text: watermark,
                            font: '22px Microsoft YaHei'
                        }
                    }
                ]
            }
        ]
    }
}

// 获取正常折线图的数据点
function getLineSeriesPoints(sourceData, column_index) {
    return sourceData.map(item=>{return parseFloat(item[column_index])})
}

// 生成series和图例的函数
function getSeriesLegend(seriesData, sourceData, sheetHeaders) {
    let len = seriesData.length;
    let seriesArray = [];
    let legend = {bottom: 18, "data":[]};
    for(let i = 0; i < len; i++) {
        let optData = seriesData[i];
        let points = getLineSeriesPoints(sourceData, optData.column_index)
        let seriesOption = {
            type: optData.chart_type,
            // name: optData.chart_name,
            symbol: 'circle',
            name: sheetHeaders[optData.column_index],
            yAxisIndex: optData.axis_index,
            connectNulls: true,
            // data: sourceData.map(item=>{return parseFloat(item[optData.column_index])})
            data: points
        };
        // 改为单点
        if (points.length === 1){
            seriesOption = {
                type: 'scatter',
                name: sheetHeaders[optData.column_index],
                yAxisIndex: 0,
                symbolSize: 8,
                data: points
            }
        }
        seriesArray.push(seriesOption);
        legend.data.push(sheetHeaders[optData.column_index],);
    }
    return {
        seriesData: seriesArray,
        legendData: legend
    }
}

// 获取季节图数据点
function getSeriesPoints(yearData,column_index) {
    return yearData.map(item=>{return [item["column_0"], item[column_index]]})
}

// 获取图形序列和图例
function getSeasonSeriesLegend(seriesData, sourceData){
    let optData = seriesData[0];
    let seriesArray = [];
    let legend = {bottom: 18, "data":[]};
    for(let yearKey in sourceData){
        if (yearKey === "xAxisData"){continue}
        let yearData = sourceData[yearKey];
        let seriesPoints = getSeriesPoints(yearData, optData.column_index)
        let seriesOption = {
            type: "line",
            symbol: 'circle',
            name: yearKey,
            yAxisIndex: 0,
            connectNulls: true,
            // data: yearData.map(item=>{return [item["column_0"], item[optData.column_index]]})
            data: seriesPoints
        };
        // 改为单点
        if (seriesPoints.length === 1){
            seriesOption = {
                type: 'scatter',
                name: yearKey,
                yAxisIndex: 0,
                symbolSize: 8,
                data: seriesPoints
            }
        }
        seriesArray.push(seriesOption);
        legend.data.push(yearKey)
    }

    return {
        seriesData: seriesArray,
        legendData: legend
    }
}

// 计算图例所占的行数
function calculateLegendRowCount(legendData){
    // legendData是一个数组
    // 每个图例的宽度 = 图例标记(echarts固定宽) + 字符数 * 每个字符所需宽度
    // echarts默认图例间隔itemGap = 10;默认图例标记宽度itemWidth = 25;默认图例标记高度itemHeight = 14
    // echarts图例默认字体大小12，默认各内边距5
    // 得一个图例所需要的宽度为25 + 5 + 字符数 * 12 + 5 + 10 = 45 + 字符数 * 12
    // 图形显示区域总宽度在class中定义为600
    let usedWidth = 0
    let count = 1
    legendData.forEach((item, index) => {
        const eachWidth = 45 + getStrWidth(item, 12)
        if (600 - usedWidth < eachWidth){
            count = count + 1
            usedWidth = 0
        }
        usedWidth = usedWidth + eachWidth
    })
    return count
}


// 生成季节图形的配置
function generateSeasonOption(baseOption, sourceData, sheetHeaders){
    let chartTitle = baseOption["title"];
    const xAxis_show_max_label = baseOption.x_axis.showMaxLabel?true:null
    let seriesLegend = getSeasonSeriesLegend(baseOption.series_data, sourceData);
    let legendRowCount = calculateLegendRowCount(seriesLegend.legendData.data)
    let extraTop = 5
    if (legendRowCount < 2){extraTop = 10}
    return {
        grid: {
            top: chartTitle["font_size"] + 15,
            left: 10,
            right: 10,
            bottom: legendRowCount * 14 + (legendRowCount - 1) * 10 + 22 + extraTop,
            show: false,
            containLabel: true
        },
        title:{
            text: chartTitle["text"],
            textStyle: {fontSize: chartTitle["font_size"]},
            left: 'center'
        },
        xAxis:{
            type: 'category',
            data: sourceData.xAxisData,
            axisLabel: {
                rotate: 90,
                fontSize: 11,
                showMaxLabel: xAxis_show_max_label
            }
        },
        yAxis: baseOption.y_axis,
        tooltip:{
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            }
        },
        dataZoom: [
            {
                show: true,
                type: 'slider',
                height: 20,
                bottom:0,
                start: 0,
                end: 100,
            }
        ],
        series: seriesLegend.seriesData,
        legend: seriesLegend.legendData,
        graphic: generateGraphic(baseOption.watermark),
    };
}


// 生成普通图形的配置
function generateOption(baseOption, sourceData, sheetHeaders){
    let chartTitle = baseOption["title"];
    const xAxis_show_max_label = baseOption.x_axis.showMaxLabel?true:null
    let seriesLegend = getSeriesLegend(baseOption.series_data, sourceData, sheetHeaders);
    let legendRowCount = calculateLegendRowCount(seriesLegend.legendData.data)
    // grid 的bottom值需 = 图例所占的行数 * 每行所占的高度14 + 22 // 其中27为伸缩条的高度20 + 间距2 + 顶部距离5
    let extraTop = 5
    if (legendRowCount < 2){extraTop = 10}
    // 处理右轴分割线
    let yaxises = baseOption.y_axis
    if (yaxises.length > 1){
        yaxises[1].splitLine={show: false}
    }
    let bottomMargin = legendRowCount * 14 + (legendRowCount - 1) * 10 + 22 + extraTop
    return {
        grid: {
            top: chartTitle["font_size"] + 15,
            left: 10,
            right: 10,
            bottom: bottomMargin,
            show: false,
            containLabel: true
        },
        title:{
            text: chartTitle["text"],
            textStyle: {fontSize: chartTitle["font_size"]},
            left: 'center'
        },
        xAxis:{
            type: 'category',
            data: sourceData.map(item=>item.column_0),
            axisLabel: {
                rotate: 90,
                fontSize: 11,
                showMaxLabel: xAxis_show_max_label
            }
        },
        yAxis: baseOption.y_axis,
        tooltip:{
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            }
        },
        dataZoom: [
            {
                show: true,
                type: 'slider',
                height: 20,
                bottom:0,
                start: 0,
                end: 100,
            }
        ],
        series: seriesLegend.seriesData,
        legend: seriesLegend.legendData,
        graphic: generateGraphic(baseOption.watermark),
    };
}


// 生成区间图形的配置
function generateIntervalOption(baseOption, sourceData, sheetHeaders){
  return {
      title: {
        text: baseOption.title.text,
        textStyle:{fontSize: baseOption.title.font_size},
        left: 'center'
      },
      tooltip: {
          trigger: 'axis',
          axisPointer: {
              type: 'cross',
              label: {
                  backgroundColor: '#6a7985'
              }
          },
          formatter: function(params,ticket,callback){
              let space = '&nbsp;&nbsp;&nbsp;&nbsp;'
              let maxVaule = parseFloat(params[0].value) + parseFloat(params[1].value)
              let str = params[0].axisValue + '<br>'
              str += params[0].seriesName + space +  params[0].value.toFixed(2) + '<br>'
              str += params[1].seriesName + space +  maxVaule.toFixed(2) + '<br>'
              str += params[2].seriesName + space +  params[2].value.toFixed(2) + '<br>'
              if(params[3]){
                str += params[3].seriesName
                if (params[3].value == '-'){str += space +  params[3].value
                }else{str += space +  params[3].value.toFixed(2)}
              }
              return str
          }
      },
      legend: {
          data: ['最小', '最大', '均值', '当前值'],
          bottom: 0
      },
      // toolbox: {
      //     feature: {
      //         saveAsImage: {}
      //     }
      // },
      grid: {
          left: '3%',
          right: '4%',
          bottom: 30,
          containLabel: true
      },
      xAxis: [
          {
              type: 'category',
              boundaryGap: false,
              // axisLabel: {
              //   showMaxLabel: true
              // },
              data: sourceData.map(item => item.month_date)
          }
      ],
      yAxis: [
          {
              type: 'value',
              scale: true
          }
      ],
      series: [
        {
            name: '最小',
            type: 'line',
            stack: 'total',
            data: sourceData.map(item => item.min),
            color: '#aaa',
            symbol: 'none'
            
        },
        {
            name: '最大',
            type: 'line',
            stack: 'total',
            areaStyle: {color: '#ddd'},
            // [200, 232, 150, 160, 110, 255, 300]
            data: sourceData.map(item => {return (item.max - item.min).toFixed(2)}),
            color: '#aaa',
            symbol: 'none'
            
        },
        {
            name: '均值',
            type: 'line',
            data: sourceData.map(item => item.mean),
            symbol: 'none'
        },
        {
            name: '当前值',
            type: 'line',
            data: sourceData.map(item => item.value),
            symbol: 'none'
        }
      ]
    }
}
</script>
{% if has_chart == 0 %}
<div class="noChart">当前数据没有图形...</div>
{% endif %}
<div class="charts">
    {% for chart in sheet_charts %}
    <div class="chart-container">
        <div style="border-bottom: 1px solid #222222">
            <div id="chart_{{ chart.id }}" style="height:337px; width: 600px;"></div>
            <div style="margin: 10px 0;color:#000;font-weight: bold">
                <div style="text-indent: 2em;line-height:25px; font-size: 13px" id="compare{{chart.id}}">

                </div>
            </div>
            <div style="margin-bottom: 10px;color:#000;font-weight: bold">
                <div style="text-indent: 2em;line-height:25px; font-size: 13px">{{chart.decipherment}}</div>
            </div>
    <script>

        $(function () {
            let comId =  document.getElementById('compare{{chart.id}}');
            $.ajax({
                type: 'GET',
                url: host + 'chart-compare/{{chart.id}}/', // 请求对比解读
                dataType: 'json',
                success: function (res) {
                    comId.innerHTML = res.compare_text
                }
            })
        })
    $(function () {
        let charDiv = document.getElementById('chart_{{chart.id}}');
        let chartObj = echarts.init(charDiv, 'red', {render:'canvas'});
        $.ajax({
         type:'GET',
         url: host + 'chart-option/{{chart.id}}/',  //  请求当前表的配置和数据
         dataType: 'json',
         success:function(result){
             let chart_type = result.chart_type;
             let option = {};
             if (chart_type === "normal"){
                option = generateOption(result.base_option, result.chart_values, result.sheet_headers);
             }
             if (chart_type === "season"){
                option = generateSeasonOption(result.base_option, result.chart_values, result.sheet_headers);
             }
             if (chart_type === "interval"){
               option = generateIntervalOption(result.base_option, result.chart_values, result.sheet_headers);
             }
             chartObj.setOption(option, true)

             // chart.setOption(result.options);
         }
        });
    })
    </script>
    </div>
    </div>
    {% endfor %}
</div>
</body>
</html>